//
//  HMRefreshController.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/7/5.
//  Copyright © 2015年 HeiMa. All rights reserved.
//

import UIKit
import FFAutoLayout

class HMRefreshController: UIRefreshControl {
    
    override init() {
        super.init()
        addSubview(refreshView)
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    // 是否显示提示图标标记
    private var showTipFlag = false
    // 正在加载标记
    private var loadingFlag = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0{
            return
        }
//        print(frame)
        
        if refreshing && !loadingFlag {
            refreshView.startLoadingAnim()
            loadingFlag = true
            return
        }
        
        if frame.origin.y < -50 && !showTipFlag {
            print("翻过来")
            showTipFlag = true
            refreshView.rotateTipIcon(showTipFlag)
        } else if frame.origin.y >= -50 && showTipFlag {
            print("转过去")
            showTipFlag = false
            refreshView.rotateTipIcon(showTipFlag)
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        // 关闭动画
        refreshView.stopLoadingAnim()
        // 重设刷新标记
        loadingFlag = false
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var refreshView = HMRefreshView.refreshView()
}

class HMRefreshView: UIView {
    // 加载图标
    @IBOutlet weak var loadingIcon: UIImageView!
    // 下拉图标容器
    @IBOutlet weak var tipView: UIView!
    // 下拉图标
    @IBOutlet weak var tipIcon: UIImageView!
    
    // 返回下拉加载视图的类方法
    class func refreshView() ->HMRefreshView {
        return NSBundle.mainBundle().loadNibNamed("HMRefreshView", owner: nil, options: nil).last as! HMRefreshView
    }
    
    ///  旋转提示图标
    private func rotateTipIcon(clockWise: Bool){
        var angle = M_PI
        angle += clockWise ? -0.01 : 0.01
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(angle))
        }
    }
    
    // 开启加载动画
    private func startLoadingAnim(){
       tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        loadingIcon.layer.addAnimation(anim, forKey: nil)
    }
    
    private func stopLoadingAnim(){
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }
}




